package com.wolfalpha.lwtool.activity;

import java.util.HashMap;
import java.util.Map;

import com.wolfalpha.lwtool.R;
import com.wolfalpha.lwtool.constant.Constant;
import com.wolfalpha.lwtool.service.impl.UserServiceImpl;
import com.wolfalpha.lwtool.vo.LWCompany;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author ttStudio
 * 
 */
public class AuditeComActivity extends Activity {
	private ProgressDialog pd;
	private UserServiceImpl sav;
	private Button submit;// 审核提交
	private Button reason_demo;// 审核提交
	private EditText reason_content;// 审核提交
	private RadioGroup operation;
	private String cf = "";
	private String reason = "";
	private int mid;
	private LWCompany mCom = null;
	@SuppressLint("UseSparseArrays")
	Map<Integer, String> jobCategoryMap = new HashMap<Integer, String>();
	@SuppressLint("UseSparseArrays")
	Map<Integer, String> wageTypeUnitMap = new HashMap<Integer, String>();

	private WebView image;

	private String[][] items = new String[][] {
			{ "其他", "兼职信息填写不详细", "兼职信息填写不真实", "联系人电话无效", "兼职信息不合法", "疑似虚假信息",
					"被评定为中介", "经验证，信息符合规定，允许发布。" },
			{ "其他", "上传营业执照不清晰", "企业信息不完善", "联系人电话无效", "疑似虚假信息", "被评定为中介" } };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sav = new UserServiceImpl();
		setContentView(R.layout.activity_audite_com);

		initView();
		initListeners();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// menu.add(Menu.NONE, Menu.FIRST + 1, 1, "全部通过");
		// menu.add(Menu.NONE, Menu.FIRST + 2, 1, "全部删除");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			handler.sendEmptyMessage(TOASTA);
			break;
		case Menu.FIRST + 2:
			handler.sendEmptyMessage(TOASTA);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private static final int TOASTA = 1;
	private static final int TRYUPDATE = 2;

	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case TOASTA:
				pd = new ProgressDialog(AuditeComActivity.this);
				pd.setMessage("正在准备。。。");
				pd.setCancelable(false);
				if (!pd.isShowing())
					pd.show();
				break;
			case TRYUPDATE:
				new MyTask().execute();
				break;
			}

		}

	};
	private TextView cuser_id;
	private TextView cname;
	private TextView clocation;
	private TextView ccategory;
	private TextView cweb;
	private TextView ctel;
	private TextView cintro;
	private TextView ccontact;
	private TextView csize;
	private TextView cfield;
	private TextView cmail;
	private TextView caddress;
	private TextView clicence;
	private TextView cpic;
	private TextView cis_audited;

	/**
	 * 此方法必须重写，以决绝退出activity时 dialog未dismiss而报错的bug
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		try {
			pd.dismiss();
		} catch (Exception e) {
			System.out.println("pd取消，失败！");
			// TODO: handle exception
		}
		super.onDestroy();
	}

	private void initListeners() {
		reason_demo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						AuditeComActivity.this);
				builder.setItems(items[1],
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								/**
								 * ad变量用final关键字定义，因为在隐式实现的Runnable接口 的run()方法中
								 * 需要访问final变量。
								 */
								// "你选择的是：" + which + ": " + items[which])
								reason = items[1][which];
								reason_demo.setText(reason);
							}
						});
				builder.create().show();
			}
		});
		submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (operation.getCheckedRadioButtonId() == R.id.nupass) {
					if (reason.equals("其他")) {
						if (reason_content.equals("")) {
							Toast.makeText(AuditeComActivity.this,
									"审核原因为其他时请填写具体原因", Toast.LENGTH_SHORT)
									.show();
							return;
						}
					} else if (reason.equals("") && reason_content.equals("")) {
						Toast.makeText(AuditeComActivity.this, "审核原因不完整",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
				SubmitTask sb = new SubmitTask();
				sb.execute();
			}
		});
	}

	private void initView() {
		submit = (Button) findViewById(R.id.submit);
		operation = (RadioGroup) findViewById(R.id.radio_operation);
		reason_demo = (Button) findViewById(R.id.reson_demo);
		reason_content = (EditText) findViewById(R.id.reson_content);

		image = (WebView) findViewById(R.id.pic_webView);

		/** 设置调用本地WebView而非浏览器 **/
		image.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});

		// image.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent arg1) {
		// if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
		// int temp_ScrollY = image.getScrollY();
		// image.scrollTo(image.getScrollX(), image.getScrollY() + 1);
		// image.scrollTo(image.getScrollX(), temp_ScrollY);
		// }
		//
		// return false;
		// }
		// });

		WebSettings webSettings = image.getSettings();
		webSettings.setUseWideViewPort(false);// 设置此属性，可任意比例缩放
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		cuser_id = (TextView) findViewById(R.id.cuser_id);
		cname = (TextView) findViewById(R.id.cname);
		clocation = (TextView) findViewById(R.id.clocation);
		cweb = (TextView) findViewById(R.id.cweb);
		ctel = (TextView) findViewById(R.id.ctel);
		ccontact = (TextView) findViewById(R.id.ccontact);
		cintro = (TextView) findViewById(R.id.cintro);
		csize = (TextView) findViewById(R.id.csize);
		cfield = (TextView) findViewById(R.id.cfield);
		ccategory = (TextView) findViewById(R.id.ccategory);
		cmail = (TextView) findViewById(R.id.cmail);
		caddress = (TextView) findViewById(R.id.caddress);
		clicence = (TextView) findViewById(R.id.clicence);
		cpic = (TextView) findViewById(R.id.cpic);
		cis_audited = (TextView) findViewById(R.id.cis_audited);

		/** 审核兼职 */
		MyTask mt = new MyTask();
		mt.execute();
	}

	private void displayView() {
		cuser_id.setText(mCom.getUser_id());
		cname.setText(mCom.getName());
		clocation.setText(mCom.getLocation());
		cweb.setText(mCom.getWebsite());
		ctel.setText(mCom.getTel());
		ccontact.setText(mCom.getContact());
		cintro.setText(mCom.getIntro());
		csize.setText(mCom.getSize());
		cfield.setText(jobCategoryMap.get(mCom.getField()));
		ccategory.setText(mCom.getCategory());
		cmail.setText(mCom.getEmail());
		caddress.setText(mCom.getAddress());
		clicence.setText(mCom.getLicense());
		cpic.setText(mCom.getLicense_pic());
		cis_audited.setText(mCom.getIs_audited() == 1 ? "是" : "否");
	}

	private class MyTask extends AsyncTask<String, Integer, String> {

		// onPreExecute方法用于在执行后台任务前做一些UI操作
		@Override
		protected void onPreExecute() {
			if (pd == null)
				pd = new ProgressDialog(AuditeComActivity.this);
			pd.setMessage("正在更新信息");
			pd.setCancelable(false);
			if (!pd.isShowing())
				pd.show();
		}

		// doInBackground方法内部执行后台任务,不可在此方法内修改UI
		@SuppressLint("CommitPrefEdits")
		@Override
		protected String doInBackground(String... params) {

			String[] array1 = AuditeComActivity.this.getResources()
					.getStringArray(R.array.work_style_array);
			for (int i = 0; i < array1.length; i++) {
				jobCategoryMap.put(i, array1[i]);// 0 全部类型 1 其他 2 销售 ....
			}

			String[] array2 = AuditeComActivity.this.getResources()
					.getStringArray(R.array.money_style_array_2);
			for (int i = 0; i < array2.length; i++) {
				wageTypeUnitMap.put((i + 1), array2[i]);// 1 元/时 2元/天
			}

			try {
				cf = sav.adminViewInfo(2);
				if (cf.equals("") || cf == null) {
					this.cancel(true);
				}

				cf = cf.split("\\}")[0];
				cf = cf.replaceAll("\\[", "");
				cf = cf.replaceAll("\\{", "");

				mCom = new LWCompany(cf);
				mid = Integer.parseInt(mCom.getUser_id());
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Failed");
				this.cancel(true);
			}
			return null;
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(String result) {
			new GetPicTask().execute();

		}

		// onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			Toast.makeText(AuditeComActivity.this, "没有企业信息", Toast.LENGTH_SHORT)
					.show();
			if (pd.isShowing())
				pd.dismiss();
		}
	}

	private class SubmitTask extends AsyncTask<String, Integer, String> {

		// onPreExecute方法用于在执行后台任务前做一些UI操作
		@Override
		protected void onPreExecute() {
			if (pd == null)
				pd = new ProgressDialog(AuditeComActivity.this);
			pd.setMessage("正在提交");
			pd.setCancelable(false);
			if (!pd.isShowing())
				pd.show();
		}

		// doInBackground方法内部执行后台任务,不可在此方法内修改UI
		@SuppressLint("CommitPrefEdits")
		@Override
		protected String doInBackground(String... params) {
			try {
				if (!cf.equals("")) {
					int isPass = 0;
					int i = operation.getCheckedRadioButtonId();
					switch (i) {
					case R.id.pass:
						isPass = 1;
						break;
					case R.id.nupass:
						isPass = 0;
						break;
					case R.id.delete:
						isPass = 3;
						break;
					default:
						isPass = 0;
						break;
					}
					try {
						if (!sav.adminAudite(2, mid, isPass, reason,
								reason_content.getText().toString())) {
							this.cancel(true);
						}
					} catch (Exception e) {
						this.cancel(true);
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Failed");
				this.cancel(true);
			}
			return null;
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(AuditeComActivity.this, "审核提交成功", Toast.LENGTH_SHORT)
					.show();
			if (pd.isShowing())
				pd.dismiss();
			handler.sendEmptyMessage(TRYUPDATE);
			AuditeComActivity.this.finish();
		}

		// onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			Toast.makeText(AuditeComActivity.this, "提交失败,请重试",
					Toast.LENGTH_SHORT).show();
			if (pd.isShowing())
				pd.dismiss();
		}
	}

	private class GetPicTask extends AsyncTask<String, Integer, String> {

		private String p_url;

		// onPreExecute方法用于在执行后台任务前做一些UI操作

		@Override
		protected void onPreExecute() {
		}

		// doInBackground方法内部执行后台任务,不可在此方法内修改UI
		@SuppressLint("CommitPrefEdits")
		@Override
		protected String doInBackground(String... params) {
			try {
				p_url = sav.getComLicPic(mid);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Failed");
				this.cancel(true);
			}
			return null;
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(String result) {
			if (p_url != "" || p_url != null)
				image.loadUrl(Constant.serverUrl + p_url);// 加载到ImageView上
			displayView();
			if (pd.isShowing())
				pd.dismiss();
		}
	}

}
